﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using Configuration.ServerApi.Param;
using System;
using System.Threading.Tasks;

namespace Configuration.ServerApi.Filter
{
    /// <summary>
    /// 自定义异常过滤器
    /// </summary>
    public class CustomerExceptionFilter : IAsyncExceptionFilter
    {
        /// <summary>
        /// 重写OnExceptionAsync方法，定义自己的处理逻辑
        /// </summary>
        /// <param name="context">异常内容</param>
        /// <returns></returns>
        public Task OnExceptionAsync(ExceptionContext context)
        {
            // 如果异常没有被处理则进行处理
            if (context.ExceptionHandled == false)
            {
                // 定义返回类型
                var result = new ResultModel
                {
                    Code = 0,
                    Success = false,
                    Msg = "API访问异常, 请参考Data内容检查错误原因",
                    Count = 0,
                    Data = context.Exception.Message
                };

                // 记录异常日志
                _ = Task.Run(() => { Console.WriteLine(context.Exception); NLog.Error(context.Exception); });

                // Token 失效错误码
                if (context.Exception.Message.Contains("Sequence contains no matching element"))
                {
                    context.Result = new ContentResult
                    {
                        // 返回状态码设置为401，表示Token失效
                        StatusCode = StatusCodes.Status401Unauthorized,
                        // 设置返回格式
                        ContentType = "application/json;charset=utf-8",
                        Content = JsonConvert.SerializeObject(result)
                    };
                }
                else
                {
                    context.Result = new ContentResult
                    {
                        // 返回状态码设置为200，表示成功
                        StatusCode = StatusCodes.Status200OK,
                        // 设置返回格式
                        ContentType = "application/json;charset=utf-8",
                        Content = JsonConvert.SerializeObject(result)
                    };
                }
            }
            // 设置为true，表示异常已经被处理了
            context.ExceptionHandled = true;
            return Task.CompletedTask;
        }

    }
}
